package com.yhh.college_information_platform.controller;

import com.yhh.college_information_platform.annotation.PublicAccess;
import com.yhh.college_information_platform.annotation.RequireAuth;
import com.yhh.college_information_platform.common.PageResult;
import com.yhh.college_information_platform.common.Result;
import com.yhh.college_information_platform.dto.SearchDTO;
import com.yhh.college_information_platform.service.SearchService;
import com.yhh.college_information_platform.vo.ResourceVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 搜索Controller
 *
 * @author yhh
 * @date 2025-10-26
 */
@Slf4j
@RestController
@RequestMapping("/search")
public class SearchController {

    @Autowired
    private SearchService searchService;

    /**
     * 全局搜索资料（游客可访问）
     */
    @PublicAccess
    @PostMapping("/resources")
    public Result<PageResult<ResourceVO>> searchResources(
            @RequestBody SearchDTO searchDTO,
            HttpServletRequest request) {
        
        // 获取用户ID（可能为null，未登录用户也可以搜索）
        Long userId = (Long) request.getAttribute("userId");
        
        PageResult<ResourceVO> result = searchService.searchResources(searchDTO, userId);
        return Result.success(result);
    }

    /**
     * 获取用户搜索历史（需要登录）
     */
    @RequireAuth
    @GetMapping("/history")
    public Result<List<String>> getSearchHistory(
            @RequestParam(defaultValue = "10") Integer limit,
            HttpServletRequest request) {
        
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error(401, "请先登录");
        }
        
        List<String> history = searchService.getUserSearchHistory(userId, limit);
        return Result.success(history);
    }

    /**
     * 删除搜索历史（需要登录）
     */
    @RequireAuth
    @DeleteMapping("/history")
    public Result<Void> deleteSearchHistory(
            @RequestParam(required = false) String keyword,
            HttpServletRequest request) {
        
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error(401, "请先登录");
        }
        
        searchService.deleteSearchHistory(userId, keyword);
        return Result.success();
    }

    /**
     * 获取热门搜索关键词（游客可访问）
     */
    @PublicAccess
    @GetMapping("/hot")
    public Result<List<String>> getHotKeywords(
            @RequestParam(defaultValue = "10") Integer limit) {
        
        List<String> hotKeywords = searchService.getHotKeywords(limit);
        return Result.success(hotKeywords);
    }
}

